<template>
    <el-dialog :model-value="true" :show-close="false" title="添加商品">

        <el-form ref="formRef" :model="form" :rules="rules">
            <el-form-item prop="name" label="名称">
                <el-input v-model="form.name" placeholder="名称" />
            </el-form-item>
            <el-form-item prop="price" label="商品价格">
                <el-input v-model="form.price" type="number" placeholder="商品价格" />
            </el-form-item>
            <el-form-item prop="category_id" label="商品分类">
                <Select v-model="form.category_id" :options="categoryList"/>
            </el-form-item>
            <el-form-item prop="description" label="商品详情">
                <el-input v-model="form.description" placeholder="商品详情" />
            </el-form-item>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="$emit('close')" :disabled="loading">取消</el-button>
                <AsyncButton :loading="loading" type="primary" @click="submitForm(formRef)">
                    确认
                </AsyncButton>
            </span>
        </template>
    </el-dialog>
</template>
  
<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { addProduct, getAllCategory } from '@/api/index'
import Select from '@/components/select/index.vue'

const emit = defineEmits()

const form = ref({
    name: '',
    price: '',
    description: '',
    category_id: '',
});

const rules = {
    name: [
        { required: true, message: '请输入商品名称' },
    ],
    price: [
        { required: true, message: '请输入商品价格' },
    ],
}

const formRef = ref(null);

const loading = ref(false)

const categoryList = ref([])

onMounted(() => {
    getAllCategory().then(res => {
        console.log(res, 'getAllCategory')
        if(res.code === 200){
            categoryList.value = res.data
        }else{
            ElMessage.error(res.msg)
        }
    })
})

function submitForm(formRef){
    formRef.validate(valid => {
        if(valid){
            loading.value = true
            form.value.price = Number(form.value.price)
            addProduct(form.value).then(res => {
                console.log(res, 'res')
                loading.value = false
                if(res.code === 200){
                    emit('done');
                    ElMessage.success(res.msg)
                }else{
                    ElMessage.error(res.msg)
                }
            }).catch(err => {
                loading.value = false
            })
        }
    });
}
</script>